package com.shujia.spark.stream

import org.apache.kafka.clients.consumer.ConsumerRecord
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.streaming.dstream.{DStream, InputDStream}
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe
import org.apache.spark.streaming.kafka010.KafkaUtils
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent
import org.apache.spark.streaming.{Durations, StreamingContext}
import org.apache.spark.{SparkConf, SparkContext}

object Demo7SparkOnKafkaStudent {
  def main(args: Array[String]): Unit = {

    val conf: SparkConf = new SparkConf()
      .setMaster("local[2]")
      .setAppName("wc")

    val sc = new SparkContext(conf)

    /**
      * 创建spark streaming环境
      *
      */

    val ssc = new StreamingContext(sc, Durations.seconds(5))

    ssc.checkpoint("data/checkpoint")


    val kafkaParams: Map[String, Object] = Map[String, Object](

      "bootstrap.servers" -> "master:9092,node1:9092,node2:9092", //froker 列表
      "key.deserializer" -> classOf[StringDeserializer], //key 反序列化的列
      "value.deserializer" -> classOf[StringDeserializer],
      "group.id" -> "asdasdasd", //消费者组, 同一条数据在一个组内只被消费一次
      "auto.offset.reset" -> "earliest" // 消费数据的位置（latest： 读最新数据）
    )

    /**
      * earliest
      * 当各分区下有已提交的offset时，从提交的offset开始消费；无提交的offset时，从头开始消费
      * latest
      * 当各分区下有已提交的offset时，从提交的offset开始消费；无提交的offset时，消费新产生的该分区下的数据
      * none
      * topic各分区都存在已提交的offset时，从offset后开始消费；只要有一个分区不存在已提交的offset，则抛出异常
      *
      */

    //topic
    val topics = Array("student3")

    /**
      * 创建的Dtreams是一个kv格式的，key一般没有用
      *
      */

    //链接kafka 创建DStream
    val stream: InputDStream[ConsumerRecord[String, String]] = KafkaUtils.createDirectStream[String, String](
      ssc,
      PreferConsistent,
      Subscribe[String, String](topics, kafkaParams)
    )

    //解析数据
   val studentDS: DStream[(Int, Long, Long, String, String)] =  stream.map(record => {
      val partition: Int = record.partition()
      val offset: Long = record.offset()
      val ts: Long = record.timestamp()
      val key: String = record.key()
      val value: String = record.value()
      (partition, offset, ts, key, value)
    })

    studentDS.print()

    ssc.start()
    ssc.awaitTermination()
    ssc.stop()


  }

}
